package com.seocoo.worker.base.version;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.StrictMode;
import android.support.v4.content.FileProvider;
import android.util.Log;

import com.sfh.lib.AppCacheManager;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashSet;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

/**
 * 功能描述:APK 工具
 *
 */
public class ApkCheckUtils {
    private static Set<String> fileItemList = new HashSet<String>();

    static {
        fileItemList.add("META-INF/CERT.RSA");
        fileItemList.add("META-INF/CERT.SF");
        fileItemList.add("META-INF/MANIFEST.MF");
        fileItemList.add("AndroidManifest.xml");
        fileItemList.add("resources.arsc");
        fileItemList.add("classes.dex");
    }

    /***
     * Apk安装包安装前进行检测，是否能够正确解析，避免安装时安装包解析出错，无法安装
     * @param apkPath
     * @return
     */
    public static boolean isLegalApk(String apkPath) {
        boolean result = true;

        ZipFile zipFile = null;
        ZipInputStream zipInput = null;
        try {
            File file = new File(apkPath);
            zipFile = new ZipFile(file);
            zipInput = new ZipInputStream(new FileInputStream(file));

            ZipEntry entry;
            while ((entry = zipInput.getNextEntry()) != null) {
                if (fileItemList.contains(entry.getName())) {
                }
            }
        } catch (Exception e) {
            result = false;
            e.printStackTrace();
        } finally {
            if (zipInput != null) {
                try {
                    zipInput.close();
                } catch (Exception e) {
                    result = false;
                }
            }
            if (zipFile != null) {
                try {
                    zipFile.close();
                } catch (Exception e) {
                    result = false;
                }
            }
        }
        return result;
    }


    /***
     * 安装
     * @param context
     * @param file
     */
    public static void installApk(Context context, File file,String auth) {
        if (!file.exists()) {
            return;
        }

        Uri uri = Uri.fromFile(file);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //android 7.0及以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri  = FileProvider.getUriForFile(context, auth, file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        }
        try {
            context.startActivity(intent);
        }catch (Exception e){
        }
    }


    /**
     * 本地安装版本号text
     *
     * @return
     */
    public static int getLocationVersionCode() {

        try {
            Application context = AppCacheManager.getApplication();
            PackageInfo packageInfo = context.getApplicationContext()
                    .getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (Exception e) {
            Log.e(ApkCheckUtils.class.getSimpleName(), "getLocationVersionCode: ", e);
        }

        return -1;
    }

    public static void initAppInstallUriExposure() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
            builder.detectFileUriExposure();
        }
    }
}
